package shuishijie.suishijie.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;



import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import shuishijie.suishijie.R;


/**
 * Created by zhangrl on 2016/5/17.
 */
public class AppUtil {

    public static boolean isEmpty(Object obj) {
        boolean ret = false;
        if (obj == null) {
            ret = true;
        } else if (obj instanceof Collection) {
            ret = ((Collection) obj).isEmpty();
        } else if (obj instanceof String) {
            ret = ((String) obj).isEmpty();
        }
        return ret;
    }

    public static int parseInt(String str) {
        int ret = 0;
        try {
            ret = Integer.parseInt(str);
        } catch (Exception e) {

        }
        return ret;
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("^[0-9]\\d*$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static double parseDouble(String str) {
        double ret = 0f;
        try {
            ret = Double.parseDouble(str);
        } catch (Exception e) {

        }
        return ret;
    }

    public static long parseLong(String str) {
        long ret = 0;
        try {
            ret = Long.parseLong(str);
        } catch (Exception e) {

        }
        return ret;
    }

    public static final String STAR = "**************************************";

    public static String hideIdCardInfo(String id) {
        String ret = id;
        if (!TextUtils.isEmpty(id)) {
            int start = id.length() / 3;
            int end = id.length() * 2 / 3;
            if (start < end) {
                ret = id.substring(0, start) + STAR.substring(0, end - start) + id.substring(end, id.length());
            }
        }
        return ret;
    }

    /**
     * 从assets中读取h5版本号
     *
     * @return
     */
    public static int getHtmlVersionFromAssets(Context context) {
        InputStreamReader inputReader = null;
        BufferedReader bufReader = null;
        try {
            inputReader = new InputStreamReader(context.getResources().getAssets()
                    .open("h5/htmlversion.txt"));
            bufReader = new BufferedReader(inputReader);
            String line = bufReader.readLine();
            String[] strs = line.split("=");
            int version = Integer.parseInt(strs[1]);
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputReader != null) {
                try {
                    inputReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufReader != null) {
                try {
                    bufReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return 0;
    }

    /**
     * 从程序目录里读取h5版本号
     */
    public static int getHtmlVersionFromDir(Context context, String updateFolder) {
        int version = 0;
        FileInputStream fileInputStream = null;
        try {
            String path = updateFolder + File.separator + "htmlversion.txt";
            if (new File(path).exists()) {
//				fileInputStream = context.openFileInput(updateFolder + File.separator + "htmlversion.txt");
                fileInputStream = new FileInputStream(new File(path));
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
                String versionLine = bufferedReader.readLine();
                bufferedReader.close();
                if (!TextUtils.isEmpty(versionLine) && versionLine.startsWith("htmlVersion=")) {
                    version = Integer.parseInt(versionLine.substring("htmlVersion=".length()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    // nothing
                }
            }
        }
        return version;
    }
//
//	public static boolean isTV(Context context) {
//		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//		Display display = wm.getDefaultDisplay();
//
//		DisplayMetrics dm = new DisplayMetrics();
//		display.getMetrics(dm);
//		double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
//		double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
//		// 屏幕尺寸
//		double screenInches = Math.sqrt(x + y);
//		// 大于14尺寸则为TV
////		if(BuildConfig.DEBUG && Build.MODEL.equals("HUAWEI HN3-U01")) {
////			return true;
////		}
//		return screenInches >= 14.0;
//	}

    public static boolean isScreenOn(Context context) {
        boolean ret = true;
        if (context != null) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            ret = pm.isScreenOn();
        }
        return ret;
    }

    /**
     * 获取当前应用的版本号
     */
    public static String getVersionCode(Context context) {
        String version = "";
        try {
            // 获取packagemanager的实例
            PackageManager packageManager = context.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            version = packInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
            stringBuilder.append(" ");
        }
        return stringBuilder.toString();
    }

    public static boolean checkBcc(byte[] bytes) {
        return bytes == null ? false : getBcc(bytes, bytes.length) == 0;
    }

    public static byte getBcc(byte[] bytes, int len) {
        byte checkSum = 0;
        for (int i = 0; i < len && i < bytes.length; i++) {
            checkSum ^= bytes[i];
        }
        return checkSum;
    }

    private static final String ANDROID_RESOURCE = "android.resource://";
    private static final String FOREWARD_SLASH = "/";

    public static Uri resourceIdToUri(Context context, int resourceId) {
        return Uri.parse(ANDROID_RESOURCE + context.getPackageName() + FOREWARD_SLASH + resourceId);
    }

    public static <T> List<T> deepCopyList(List<T> src) {
        List<T> dest = null;
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(src);
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream in = new ObjectInputStream(byteIn);
            dest = (List<T>) in.readObject();
        } catch (IOException e) {
            e.printStackTrace();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return dest;
    }

    private static final int[] goodsTitleTagId = {0, R.mipmap.icon_goods_tag1, R.mipmap.icon_goods_tag2, R.mipmap.icon_goods_tag3};

    public static void setGoodsTag(final TextView textView, String strTag) {
        int tag = AppUtil.parseInt(strTag);
//        if (tag >= 0 && tag <= goodsTitleTagId.length) {
//            textView.setCompoundDrawablesWithIntrinsicBounds(goodsTitleTagId[tag], 0, 0, 0);
//        }
        final Html.ImageGetter imageGetter = new Html.ImageGetter() {

            public Drawable getDrawable(String source) {
                Drawable drawable = null;
                int rId = Integer.parseInt(source);
                drawable = textView.getResources().getDrawable(rId);
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                return drawable;
            }
        };


        String text = "";
        if ((tag & 1) == 1) {
            text += "<img src=\"" + R.mipmap.icon_goods_tag1 + "\" /> ";
        }
        if ((tag & 2) == 2) {
            text += "<img src=\"" + R.mipmap.icon_goods_tag2 + "\" /> ";
        }
        if ((tag & 4) == 4) {
            text += "<img src=\"" + R.mipmap.icon_goods_tag3 + "\" /> ";
        }

        text += textView.getText().toString();
        textView.setText(Html.fromHtml(text, imageGetter, null));
    }

//    public static void setImage(ImageView imageView, String path, int placeHolder) {
//        setImage(GlideApp.with(imageView), imageView, path, placeHolder);
//    }
//
//    public static void setImage(ImageView imageView, String path) {
//        setImage(GlideApp.with(imageView), imageView, path, R.drawable.defalt_img);
//    }
//
//    public static void setImage(GlideRequests glideManager, ImageView imageView, String path, int placeHolder) {
//        GlideRequest<Drawable> load = glideManager.load(path);
//        if (placeHolder != 0) {
//            load.placeholder(placeHolder);
//        }
//        load.diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
//    }

    public static Date parserDate(String date) {
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date ctime = new Date();
        try {
            ctime = formatter.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ctime;
    }

    public static String dateFormat(Date date) {
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat("yyyy-MM-dd");
        String ctime = formatter.format(date);
        return ctime;
    }

    public static String dateTimeFormat(Date date) {
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ctime = formatter.format(date);
        return ctime;
    }


//    /**
//     * 获取手机imse号
//     *
//     * @param context 上下文
//     * @return
//     */
    @SuppressLint("MissingPermission")
//    public static String getPhoneInfo(Context context) {
//
//        String udid = JPushInterface.getUdid(context);
//
//        /**
//         * 设备唯一号为空时，设置为mac地址
//         */
//        if (TextUtils.isEmpty(udid)) {
//            TelephonyManager tm = (TelephonyManager) context
//                    .getSystemService(Context.TELEPHONY_SERVICE);
//            udid = tm.getDeviceId();
//        }
//        /**
//         * 设备唯一号还为空时，fuck~~临时生成一个吧
//         */
//        if (TextUtils.isEmpty(udid)) {
//            udid = AppDBHelper.getInstance().getConfigValue("ENS");
//            if (TextUtils.isEmpty(udid)) {
//                udid = (Build.BRAND + "-" + Build.BOARD + "-" + Long.toHexString(System.currentTimeMillis())).replace(" ", "");
//                AppDBHelper.getInstance().setConfigValue("ENS", udid);
//            }
//        }
//
//        return udid;
//    }

    public static String getMoneyStr(double money) {
        return getMoneyStr(money, true);
    }

    public static String getMoneyStr(double money, boolean mark) {
        return getMoneyStr(money, mark, true);
    }

    public static String getMoneyStr(double money, boolean mark, boolean decimal) {
        String value = String.format("%.2f", money);
        if (!decimal && !TextUtils.isEmpty(value) && value.endsWith(".00")) {
            value = value.substring(0, value.length() - 3);
        }
        return (mark ? "¥" : "") + value;
    }


//    public static void showQrCode(final Activity activity, final ImageView view, final String str, final int qrcodeWidth) {
//        new Thread(() -> {
//            final Bitmap bitmap = createQRCode(str, qrcodeWidth);
//            activity.runOnUiThread(() -> view.setImageBitmap(bitmap));
//        }).start();
//    }
//
//    public static Bitmap createQRCode(String str, int widthAndHeight) {
//        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
//        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//        hints.put(EncodeHintType.MARGIN, 1);  //边距
//
//        BitMatrix matrix = null;
//        try {
//            if (str == null) {
//                str = "";
//            }
//            matrix = new MultiFormatWriter().encode(str,
//                    BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight, hints);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        int width = matrix.getWidth();
//        int height = matrix.getHeight();
//        int[] pixels = new int[width * height];
////        Arrays.fill(pixels, 0xffffffff);
//
//        for (int y = 0; y < height; y++) {
//            for (int x = 0; x < width; x++) {
//                if (matrix.get(x, y)) {
//                    pixels[y * width + x] = 0xff000000;
//                } else {
//                    pixels[y * width + x] = 0xfffafafa;
//                }
//            }
//        }
//        Bitmap bitmap = Bitmap.createBitmap(width, height,
//                Bitmap.Config.ARGB_8888);
//        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
//        return bitmap;
//    }
//
//    public static String getHotTimeDetail(String startTime, String endTime) {
//        StringBuilder ret = new StringBuilder();
//        long now = GloblaData.getCurrentTime();
//        long start = parserDate(startTime).getTime();
//        long end = parserDate(endTime).getTime();
//        if (start < now) {
//            long timeToStart = end - now;
//            if (timeToStart <= 0) {
//                ret.append("抢购结束");
//            } else {
//                ret.append("抢购进行中\n");
//                if (timeToStart / (24 * 60 * 60 * 1000) > 0) {
//                    ret.append(timeToStart / (24 * 60 * 60 * 1000));
//                    ret.append("天 ");
//                }
//                ret.append(String.format("%02d", (timeToStart / (60 * 60 * 1000)) % 24));
//                ret.append("时");
//                ret.append(String.format("%02d", (timeToStart / (60 * 1000)) % 60));
//                ret.append("分");
//                ret.append(String.format("%02d", (timeToStart / (1000)) % 60));
//                ret.append("秒");
//            }
//        } else {
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTimeInMillis(start);
//            ret.append(calendar.get(Calendar.MONTH) + 1);
//            ret.append("月");
//            ret.append(calendar.get(Calendar.DATE));
//            ret.append("日 ");
//
//            ret.append(String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY)));
//            ret.append(":");
//            ret.append(String.format("%02d", calendar.get(Calendar.MINUTE)));
////            ret.append("分");
////            ret.append(String.format("%02d", calendar.get(Calendar.SECOND)));
////            ret.append("秒");
//            ret.append("开抢");
//
//        }
//        return ret.toString();
//    }
//
//    public static void backToTop(RecyclerView recyclerView, View backToTop) {
//        backToTop(recyclerView, backToTop, 0);
//    }

//    /**
//     * @param recyclerView
//     * @param backToTop
//     * @param triggerType  0 滚动触发， 1 position触发
//     */
//    public static void backToTop(RecyclerView recyclerView, View backToTop, int triggerType) {
//        recyclerView.setOnFlingListener(new RecyclerView.OnFlingListener() {
//            @Override
//            public boolean onFling(int velocityX, int velocityY) {
//                if (velocityY > 2000 && recyclerView != null && recyclerView.getAdapter().getItemCount() > 5) {
//                    backToTop.setVisibility(View.VISIBLE);
//                } else if (velocityY <= 0 && triggerType == 0) {
//                    backToTop.setVisibility(View.INVISIBLE);
//                }
//                return false;
//            }
//        });
//        backToTop.setOnClickListener(v -> {
//            if (recyclerView != null && recyclerView.getAdapter().getItemCount() > 0) {
//                recyclerView.scrollToPosition(0);
//                backToTop.setVisibility(View.INVISIBLE);
//            }
//        });
//        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                if (dy > 5 && recyclerView.getAdapter().getItemCount() > 5) {
//                    int firstVisibleItems = getFirstVisiblePosition(recyclerView);
//                    if (firstVisibleItems >= 3) {
//                        backToTop.setVisibility(View.VISIBLE);
//                    }
//                } else if (dy <= 0 && triggerType == 0) {
//                    backToTop.setVisibility(View.INVISIBLE);
//                }
//                if (triggerType == 1) {
//                    if (getFirstVisiblePosition(recyclerView) < 3) {
//                        backToTop.setVisibility(View.INVISIBLE);
//                    }
//                }
//            }
//        });
//        backToTop.setVisibility(View.INVISIBLE);
//    }

    private static int getFirstVisiblePosition(RecyclerView recyclerView) {
        int[] firstVisibleItems = new int[1];
        firstVisibleItems[0] = 0;
        if (recyclerView != null) {
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager instanceof StaggeredGridLayoutManager) {
                firstVisibleItems = ((StaggeredGridLayoutManager) layoutManager).findFirstVisibleItemPositions(firstVisibleItems);
            }
            if (layoutManager instanceof GridLayoutManager) {
                firstVisibleItems[0] = ((GridLayoutManager) layoutManager).findFirstVisibleItemPosition();
            }
            if (layoutManager instanceof LinearLayoutManager) {
                firstVisibleItems[0] = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
            }
        }
        return firstVisibleItems[0];
    }
//
//    public static String getGoodsName(String name, String tag) {
//
//    }


    public static String getEmojiStringByUnicode(int unicode) {
//        try {
//            byte[] bytes = new String(Character.toChars(unicode)).getBytes("UTF-8");
//            return new String(bytes, "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            return new String(Character.toChars(unicode));
//        }
        return new String(Character.toChars(unicode));
//        return "&#" + unicode + ";";
    }

    public static void hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
        }
    }

    public static void copyToClipBoard(Context context, String text) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("", text);
        cm.setPrimaryClip(mClipData);
    }

    public static String emojiConvert1(String str) {
        String patternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";
        if (TextUtils.isEmpty(str)) {
            return str;
        }
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            try {
                int value = 0;
                String emoji = matcher.group(1);
                if (!TextUtils.isEmpty(emoji) && emoji.length() == 2) {
                    value = (emoji.charAt(0) - 0xD800) * 0x400 + 0x10000 + emoji.charAt(1) - 0xDC00;
                } else {
                    continue;
                }

                matcher.appendReplacement(
                        sb,
                        "&#x" + Integer.toHexString(value) + ";");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        matcher.appendTail(sb);
//        Logger.i("emojiConvert " + str + " to " + sb.toString()
//                + ", len：" + sb.length());
        return sb.toString();
    }

}
